//
//  RemoteListController.m
//  Podcopter
//
//  Created by Ben Gotow on 2/1/10.
//  Copyright 2010 Apple Inc. All rights reserved.
//

#import "RemoteListController.h"
#import "RemoteController.h"
#import "GamePeer.h"
#import "NetworkManager.h"

@implementation RemoteListController

 // The designated initializer.  Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) {
        // Custom initialization
		self.title = @"Select Podcopter";
    }
    return self;
}

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad 
{
    [super viewDidLoad];
    
    [[NetworkManager sharedManager] startClientSearch];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(serversUpdated:) name:@"ServersUpdated" object:nil];
}

- (void)viewWillAppear:(BOOL)animated
{
	[UIApplication sharedApplication].statusBarOrientation = UIInterfaceOrientationPortrait;	
}

- (void)serversUpdated:(NSNotification*)notif
{
    NSArray * peers = [[NetworkManager sharedManager] visibleServersArray];
    
    [tableView reloadData];
    
    if (activeConnection){
        // look to see if selectedPeer is still valid. If it's not, deselect it. Otherwise,
        // update hte selected row index so it's still shown
        if (![peers containsObject: activeConnection]){
            [activeConnection setDelegate: nil];
            [activeConnection release];
            activeConnection = nil;
        }
    }
}

- (void)didReceiveMemoryWarning 
{
    [super didReceiveMemoryWarning];
}

- (void)viewDidUnload
{
    [super viewDidUnload];
}

- (void)dealloc 
{
    [super dealloc];
}

#pragma mark TableView Data Source Functions

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)table numberOfRowsInSection:(NSInteger)section
{
    return [[[NetworkManager sharedManager] visibleServersArray] count];
}

- (UITableViewCell*)tableView:(UITableView *)tv cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"ident"];
    if (!cell) cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@"ident"] autorelease];
    
    GamePeer * conn = [[[NetworkManager sharedManager] visibleServersArray] objectAtIndex:[indexPath row]];
    [[cell textLabel] setText: [conn addressWithoutPort]];
	
    if (conn == activeConnection){
        [[cell detailTextLabel] setFont: [UIFont boldSystemFontOfSize:14]];
        if ([conn isConnecting])
            [[cell detailTextLabel] setText: @"Connecting"];
        else if ([conn isConnected])
            [[cell detailTextLabel] setText: @"Streaming Data"];
        else
            [[cell detailTextLabel] setText: @"Disconnected"];
    
    } else {
        [[cell detailTextLabel] setText: @""];
    }
    
	return cell;
}

- (void)tableView:(UITableView *)aTableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [activeConnection setDelegate: nil];
    [activeConnection release];
    activeConnection = [[[[NetworkManager sharedManager] visibleServersArray] objectAtIndex:[indexPath row]] retain];
    
    [tableView reloadData];
    [activeConnection setDelegate: self];
    [activeConnection connect];
	
	RemoteController *rc = [[RemoteController alloc] initWithNibName:@"RemoteController" bundle:nil connection:activeConnection];
	[self.navigationController pushViewController:rc animated:YES];
	[rc release];
}

#pragma mark Game Peer Delegate Functionality

- (void)gamePeerDidConnect:(GamePeer *)peer
{
    [tableView reloadData];
}

- (void)gamePeerDidDisconnect:(GamePeer *)peer
{
    [tableView reloadData];
}

- (void)gamePeerDidFailConnecting:(GamePeer *)peer
{
    [tableView reloadData];
}

- (void)gamePeerDidReceiveData:(NSData *)data
{
    // Um ok.
}


@end
